
import Sortable from 'sortablejs';
import { watch, ref, reactive, nextTick, watchEffect } from 'vue';
import eventBus from '@/utils/event-bus';

let sortable = {}
const handleDrop = (tableRef,tableOptions) => {
    nextTick().then(() => {
        const xGTable = tableRef?.value;
        sortable = Sortable.create(xGTable.$el.querySelector('.body--wrapper>.vxe-table--body tbody'), {
            handle: '.drag-btn',
            onEnd: ({ newIndex, oldIndex }) => {
                const currRow = tableOptions.data.splice(oldIndex, 1)[0];
                tableOptions.data.splice(newIndex, 0, currRow);
            }
        });
    });
}

/**左侧数据拖拽方法 */
export const useSortHandle = ({ tableRef, tableOptions }) => {
    const handleRowDrop = () => {
        handleDrop(tableRef, tableOptions)
    }
    // 监听数据源变化
    watch(() => tableOptions.data,
        (newData) => {
            eventBus.$emit('buttonGroupData', newData);
        },
        { deep: true, immediate: false }
    )
    return {
        handleRowDrop
    }
}

/**右侧数据拖拽方法 */
export const useRightSortHandle = ({ tableRef, tableOptions }) => {
    const handleRowDrop = () => {
        handleDrop(tableRef, tableOptions)
    }
    return {
        handleRowDrop
    }
}